{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f2a4d1d8",
   "metadata": {},
   "source": [
    "# Automotive Equity Research: A Multi-Step Agentic Workflow\n",
    "\n",
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_cloud_services/blob/main/examples/extract/automotive_sector_analysis.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
    "\n",
    "This notebook demonstrates an end‑to‑end agentic workflow using LlamaExtract and the LlamaIndex event‑driven workflow framework for automotive sector analysis.\n",
    "\n",
    "In this workflow, we:\n",
    "1. **Extract** key financial metrics from Q2 2024 earnings reports for Tesla and Ford.\n",
    "2. **Generate** a preliminary financial model summary for each company using an LLM.\n",
    "3. **Cross‑reference** Tesla's metrics with Ford's data to produce a final equity research memo.\n",
    "4. **Output** the memo as structured JSON.\n",
    "\n",
    "This workflow is designed for equity research analysts and investment professionals."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "880ea07c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Download an example earnings call transcript PDF from SEC EDGAR (Tesla Q2 Earnings as an example)\n",
    "!mkdir -p data/automotive_sector_analysis\n",
    "!wget https://digitalassets.tesla.com/tesla-contents/image/upload/IR/TSLA-Q2-2024-Update.pdf -O data/automotive_sector_analysis/tesla_q2_earnings.pdf\n",
    "!wget https://s205.q4cdn.com/882619693/files/doc_financials/2024/q2/Q2-2024-Ford-Earnings-Press-Release.pdf -O data/automotive_sector_analysis/ford_q2_earnings_press_release.pdf"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f2b2ea4",
   "metadata": {},
   "source": [
    "## Define the Output Schema\n",
    "\n",
    "We define a schema to represent the final equity research memo. This includes the company name, a summary of the financial model, a comparative analysis, and an overall recommendation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "492f8bf5",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pydantic import BaseModel, Field\n",
    "from typing import Optional\n",
    "\n",
    "\n",
    "class RawFinancials(BaseModel):\n",
    "    revenue: Optional[float] = Field(\n",
    "        None, description=\"Extracted revenue (in million USD)\"\n",
    "    )\n",
    "    operating_income: Optional[float] = Field(\n",
    "        None, description=\"Extracted operating income (in million USD)\"\n",
    "    )\n",
    "    eps: Optional[float] = Field(None, description=\"Extracted earnings per share\")\n",
    "    # Add more metrics as needed\n",
    "\n",
    "\n",
    "class InitialFinancialDataOutput(BaseModel):\n",
    "    company_name: str = Field(\n",
    "        ..., description=\"Company name as extracted from the earnings deck\"\n",
    "    )\n",
    "    ticker: str = Field(..., description=\"Stock ticker symbol\")\n",
    "    report_date: str = Field(..., description=\"Date of the earnings deck/report\")\n",
    "    raw_financials: RawFinancials = Field(\n",
    "        ..., description=\"Structured raw financial metrics\"\n",
    "    )\n",
    "    narrative: Optional[str] = Field(\n",
    "        None, description=\"Additional narrative content (if any)\"\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1441e681",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "FinalEquityResearchMemoOutput schema defined.\n"
     ]
    }
   ],
   "source": [
    "from pydantic import BaseModel, Field\n",
    "from typing import List, Dict\n",
    "\n",
    "\n",
    "# Define the structured output schema for each company's financial model\n",
    "class FinancialModelOutput(BaseModel):\n",
    "    revenue_projection: float = Field(\n",
    "        ..., description=\"Projected revenue for next year (in million USD)\"\n",
    "    )\n",
    "    operating_income_projection: float = Field(\n",
    "        ..., description=\"Projected operating income for next year (in million USD)\"\n",
    "    )\n",
    "    growth_rate: float = Field(..., description=\"Expected revenue growth rate (%)\")\n",
    "    discount_rate: float = Field(\n",
    "        ..., description=\"Discount rate (%) used for valuation\"\n",
    "    )\n",
    "    terminal_growth_rate: float = Field(\n",
    "        ..., description=\"Terminal growth rate (%) used in the model\"\n",
    "    )\n",
    "    valuation_estimate: float = Field(\n",
    "        ..., description=\"Estimated enterprise value (in million USD)\"\n",
    "    )\n",
    "    key_assumptions: str = Field(\n",
    "        ..., description=\"Key assumptions such as tax rate, CAPEX ratio, etc.\"\n",
    "    )\n",
    "    summary: str = Field(\n",
    "        ..., description=\"A brief summary of the preliminary financial model analysis.\"\n",
    "    )\n",
    "\n",
    "\n",
    "class ComparativeAnalysisOutput(BaseModel):\n",
    "    comparative_analysis: str = Field(\n",
    "        ..., description=\"Comparative analysis between Company A and Company B\"\n",
    "    )\n",
    "    overall_recommendation: str = Field(\n",
    "        ..., description=\"Overall investment recommendation with rationale\"\n",
    "    )\n",
    "\n",
    "\n",
    "# Define the final equity research memo schema, which aggregates the outputs for Company A and B\n",
    "class FinalEquityResearchMemoOutput(BaseModel):\n",
    "    company_a_model: FinancialModelOutput = Field(\n",
    "        ..., description=\"Financial model summary for Company A\"\n",
    "    )\n",
    "    company_b_model: FinancialModelOutput = Field(\n",
    "        ..., description=\"Financial model summary for Company B\"\n",
    "    )\n",
    "    comparative_analysis: ComparativeAnalysisOutput = Field(\n",
    "        ..., description=\"Comparative analysis between Company A and Company B\"\n",
    "    )\n",
    "\n",
    "\n",
    "print(\"FinalEquityResearchMemoOutput schema defined.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c3f8bd67",
   "metadata": {},
   "source": [
    "## Initialize the Extraction Agent\n",
    "\n",
    "We create (or replace) an extraction agent using our automotive sector analysis schema."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50ea51d7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Automotive sector analysis extraction agent created.\n"
     ]
    }
   ],
   "source": [
    "from dotenv import load_dotenv\n",
    "from llama_cloud_services import LlamaExtract\n",
    "from llama_cloud.core.api_error import ApiError\n",
    "from llama_cloud import ExtractConfig\n",
    "\n",
    "\n",
    "llama_extract = LlamaExtract(\n",
    "    project_id=\"2fef999e-1073-40e6-aeb3-1f3c0e64d99b\",\n",
    "    organization_id=\"43b88c8f-e488-46f6-9013-698e3d2e374a\",\n",
    ")\n",
    "\n",
    "try:\n",
    "    existing_agent = llama_extract.get_agent(name=\"automotive-sector-analysis\")\n",
    "    if existing_agent:\n",
    "        llama_extract.delete_agent(existing_agent.id)\n",
    "except ApiError as e:\n",
    "    if e.status_code == 404:\n",
    "        pass\n",
    "    else:\n",
    "        raise\n",
    "\n",
    "extract_config = ExtractConfig(\n",
    "    extraction_mode=\"BALANCED\"\n",
    "    # extraction_mode=\"MULTIMODAL\"\n",
    ")\n",
    "\n",
    "agent = llama_extract.create_agent(\n",
    "    name=\"automotive-sector-analysis\",\n",
    "    data_schema=InitialFinancialDataOutput,\n",
    "    config=extract_config,\n",
    ")\n",
    "print(\"Automotive sector analysis extraction agent created.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecf5cce2",
   "metadata": {},
   "source": [
    "## Define the Workflow\n",
    "\n",
    "This workflow analyzes Q2 2024 earnings reports for two major automotive companies:\n",
    "\n",
    "- **Tesla (TSLA)**: Focus on electric vehicles, energy storage, and regulatory credits\n",
    "- **Ford (F)**: Traditional automotive manufacturer with growing EV segment\n",
    "\n",
    "Key metrics extracted and analyzed:\n",
    "- Revenue and revenue projections\n",
    "- Operating income\n",
    "- Growth rates\n",
    "- Valuation estimates\n",
    "- Key business segment performance\n",
    "\n",
    "In this workflow, the steps are:\n",
    "1. **parse_transcript:** Extract text (with page citations) from the earnings call transcript PDF.\n",
    "2. **load_modeling_data:** Load financial modeling assumptions from a text file.\n",
    "3. **generate_financial_model:** Generate a preliminary financial model summary using an LLM.\n",
    "4. **load_comparable_data:** **Extract** comparable financial metrics from a PDF file (Company B).\n",
    "5. **cross_reference:** Compare Company A’s metrics with Company B’s data using the LLM.\n",
    "6. **output_final_memo:** Assemble the final equity research memo and output it as JSON."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c1f8b2f4",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/jerryliu/Programming/llama_parse/.venv/lib/python3.10/site-packages/pydantic/_internal/_fields.py:132: UserWarning: Field \"model_output\" in CompanyModelEvent has conflict with protected namespace \"model_\".\n",
      "\n",
      "You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ()`.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "from llama_index.core.workflow import (\n",
    "    Event,\n",
    "    StartEvent,\n",
    "    StopEvent,\n",
    "    Context,\n",
    "    Workflow,\n",
    "    step,\n",
    ")\n",
    "from llama_index.llms.openai import OpenAI\n",
    "from llama_index.core.llms.llm import LLM\n",
    "from llama_index.core.prompts import ChatPromptTemplate\n",
    "\n",
    "\n",
    "# Define custom events for each step\n",
    "class DeckAParseEvent(Event):\n",
    "    deck_content: InitialFinancialDataOutput\n",
    "\n",
    "\n",
    "class DeckBParseEvent(Event):\n",
    "    deck_content: InitialFinancialDataOutput\n",
    "\n",
    "\n",
    "class CompanyModelEvent(Event):\n",
    "    model_output: FinancialModelOutput\n",
    "\n",
    "\n",
    "class ComparableDataLoadEvent(Event):\n",
    "    company_a_output: FinancialModelOutput\n",
    "    company_b_output: FinancialModelOutput\n",
    "\n",
    "\n",
    "class LogEvent(Event):\n",
    "    msg: str\n",
    "    delta: bool = False\n",
    "\n",
    "\n",
    "class AutomotiveSectorAnalysisWorkflow(Workflow):\n",
    "    \"\"\"\n",
    "    Workflow to generate an equity research memo for automotive sector analysis.\n",
    "    \"\"\"\n",
    "\n",
    "    def __init__(\n",
    "        self,\n",
    "        agent: LlamaExtract,\n",
    "        modeling_path: str,\n",
    "        llm: Optional[LLM] = None,\n",
    "        **kwargs\n",
    "    ):\n",
    "        super().__init__(**kwargs)\n",
    "        self.agent = agent\n",
    "        self.llm = llm or OpenAI(model=\"o3-mini\")\n",
    "        # Load financial modeling assumptions from file\n",
    "        with open(modeling_path, \"r\") as f:\n",
    "            self.modeling_data = f.read()\n",
    "        # Instead of loading comparable data from a text file, we load from a PDF\n",
    "\n",
    "    async def _parse_deck(self, ctx: Context, deck_path) -> InitialFinancialDataOutput:\n",
    "        extraction_result = await self.agent.aextract(deck_path)\n",
    "        initial_output = extraction_result.data  # expected to be a string\n",
    "        ctx.write_event_to_stream(LogEvent(msg=\"Transcript parsed successfully.\"))\n",
    "        return initial_output\n",
    "\n",
    "    @step\n",
    "    async def parse_deck_a(self, ctx: Context, ev: StartEvent) -> DeckAParseEvent:\n",
    "        initial_output = await self._parse_deck(ctx, ev.deck_path_a)\n",
    "        await ctx.set(\"initial_output_a\", initial_output)\n",
    "        return DeckAParseEvent(deck_content=initial_output)\n",
    "\n",
    "    @step\n",
    "    async def parse_deck_b(self, ctx: Context, ev: StartEvent) -> DeckBParseEvent:\n",
    "        initial_output = await self._parse_deck(ctx, ev.deck_path_b)\n",
    "        await ctx.set(\"initial_output_b\", initial_output)\n",
    "        return DeckBParseEvent(deck_content=initial_output)\n",
    "\n",
    "    async def _generate_financial_model(\n",
    "        self, ctx: Context, financial_data: InitialFinancialDataOutput\n",
    "    ) -> FinancialModelOutput:\n",
    "        prompt_str = \"\"\"\n",
    "    You are an expert financial analyst.\n",
    "    Using the following raw financial data from an earnings deck and financial modeling assumptions,\n",
    "    refine the data to produce a financial model summary. Adjust the assumptions based on the company-specific context.\n",
    "    Please use the most recent quarter's financial data from the earnings deck.\n",
    "\n",
    "    Raw Financial Data:\n",
    "    {raw_data}\n",
    "    Financial Modeling Assumptions:\n",
    "    {assumptions}\n",
    "\n",
    "    Return your output as JSON conforming to the FinancialModelOutput schema.\n",
    "    You MUST make sure all fields are filled in the output JSON.\n",
    "\n",
    "    \"\"\"\n",
    "        prompt = ChatPromptTemplate.from_messages([(\"user\", prompt_str)])\n",
    "        refined_model = await self.llm.astructured_predict(\n",
    "            FinancialModelOutput,\n",
    "            prompt,\n",
    "            raw_data=financial_data.model_dump_json(),\n",
    "            assumptions=self.modeling_data,\n",
    "        )\n",
    "        return refined_model\n",
    "\n",
    "    @step\n",
    "    async def refine_financial_model_company_a(\n",
    "        self, ctx: Context, ev: DeckAParseEvent\n",
    "    ) -> CompanyModelEvent:\n",
    "        print(\"deck content A\", ev.deck_content)\n",
    "        refined_model = await self._generate_financial_model(ctx, ev.deck_content)\n",
    "        print(\"refined_model A\", refined_model)\n",
    "        print(type(refined_model))\n",
    "        await ctx.set(\"CompanyAModelEvent\", refined_model)\n",
    "        return CompanyModelEvent(model_output=refined_model)\n",
    "\n",
    "    @step\n",
    "    async def refine_financial_model_company_b(\n",
    "        self, ctx: Context, ev: DeckBParseEvent\n",
    "    ) -> CompanyModelEvent:\n",
    "        print(\"deck content B\", ev.deck_content)\n",
    "        refined_model = await self._generate_financial_model(ctx, ev.deck_content)\n",
    "        print(\"refined_model B\", refined_model)\n",
    "        print(type(refined_model))\n",
    "        await ctx.set(\"CompanyBModelEvent\", refined_model)\n",
    "        return CompanyModelEvent(model_output=refined_model)\n",
    "\n",
    "    @step\n",
    "    async def cross_reference_models(\n",
    "        self, ctx: Context, ev: CompanyModelEvent\n",
    "    ) -> StopEvent:\n",
    "        # Assume CompanyAModelEvent and CompanyBModelEvent are stored in the context\n",
    "        company_a_model = await ctx.get(\"CompanyAModelEvent\", default=None)\n",
    "        company_b_model = await ctx.get(\"CompanyBModelEvent\", default=None)\n",
    "        if company_a_model is None or company_b_model is None:\n",
    "            return\n",
    "\n",
    "        prompt_str = \"\"\"\n",
    "    You are an expert investment analyst.\n",
    "    Compare the following refined financial models for Company A and Company B.\n",
    "    Based on this comparison, provide a specific investment recommendation for Tesla (Company A).\n",
    "    Focus your analysis on:\n",
    "    1. Key differences in revenue projections, operating income, and growth rates\n",
    "    2. Valuation estimates and their implications\n",
    "    3. Clear recommendation for Tesla with supporting rationale\n",
    "    Return your analysis as plain text.\n",
    "    Company A Model:\n",
    "    {company_a_model}\n",
    "    Company B Model:\n",
    "    {company_b_model}\n",
    "    \"\"\"\n",
    "        prompt = ChatPromptTemplate.from_messages([(\"user\", prompt_str)])\n",
    "        comp_analysis = await self.llm.astructured_predict(\n",
    "            ComparativeAnalysisOutput,\n",
    "            prompt,\n",
    "            company_a_model=company_a_model.model_dump_json(),\n",
    "            company_b_model=company_b_model.model_dump_json(),\n",
    "        )\n",
    "        final_memo = FinalEquityResearchMemoOutput(\n",
    "            company_a_model=company_a_model,\n",
    "            company_b_model=company_b_model,\n",
    "            comparative_analysis=comp_analysis,\n",
    "        )\n",
    "        return StopEvent(result={\"memo\": final_memo})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8a3a8c1",
   "metadata": {},
   "source": [
    "## Running the Workflow\n",
    "\n",
    "Now we run the workflow with the pre-loaded modeling assumptions and the deck from both companies."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a4d5f42c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import nest_asyncio\n",
    "\n",
    "nest_asyncio.apply()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "be767dc9",
   "metadata": {},
   "outputs": [],
   "source": [
    "modeling_path = \"./data/automotive_sector_analysis/modeling_assumptions.txt\"\n",
    "workflow = AutomotiveSectorAnalysisWorkflow(\n",
    "    agent=agent, modeling_path=modeling_path, verbose=True, timeout=240\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf68b0c7",
   "metadata": {},
   "source": [
    "#### Visualize the Workflow\n",
    "\n",
    "![](data/automotive_sector_analysis/workflow_img.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b90a486",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'NoneType'>\n",
      "<class 'llama_index.core.workflow.events.StopEvent'>\n",
      "<class '__main__.DeckAParseEvent'>\n",
      "<class '__main__.DeckBParseEvent'>\n",
      "<class '__main__.CompanyModelEvent'>\n",
      "<class '__main__.CompanyModelEvent'>\n",
      "automotive_sector_analysis_workflow.html\n"
     ]
    }
   ],
   "source": [
    "from llama_index.utils.workflow import draw_all_possible_flows\n",
    "\n",
    "draw_all_possible_flows(\n",
    "    AutomotiveSectorAnalysisWorkflow,\n",
    "    filename=\"automotive_sector_analysis_workflow.html\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "70493e4f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running step parse_deck_a\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Uploading files:   0%|          | 0/1 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running step parse_deck_b\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": []
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Uploading files: 100%|██████████| 1/1 [00:00<00:00,  1.13it/s]\n",
      "Creating extraction jobs: 100%|██████████| 1/1 [00:00<00:00,  3.87it/s]\n",
      "Uploading files: 100%|██████████| 1/1 [00:01<00:00,  1.25s/it]\n",
      "Creating extraction jobs: 100%|██████████| 1/1 [00:00<00:00,  4.05it/s]\n",
      "Extracting files: 100%|██████████| 1/1 [00:03<00:00,  3.82s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step parse_deck_b produced event DeckBParseEvent\n",
      "Running step refine_financial_model_company_b\n",
      "deck content B company_name='Ford Motor Company' ticker='F' report_date='July 24, 2024' raw_financials=RawFinancials(revenue=47.8, operating_income=2.8, eps=0.46) narrative='Ford reports second-quarter revenue of $47.8 billion, net income of $1.8 billion and adjusted EBIT of $2.8 billion. Ford Pro posts quarterly EBIT of $2.6 billion – a 15% margin – on 9% revenue gain; customers buying every Super Duty truck and Transit van the company can make. Ford Blue hybrid sales up 34%, represent nearly 9% of company’s global vehicle mix; Ford Model e costs down ~$400 million. Expectations for full-year 2024 adjusted EBIT unchanged at $10 billion to $12 billion; adjusted free cash flow outlook raised $1 billion, to between $7.5 billion and $8.5 billion.'\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Extracting files: 100%|██████████| 1/1 [00:03<00:00,  3.74s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step parse_deck_a produced event DeckAParseEvent\n",
      "Running step refine_financial_model_company_a\n",
      "deck content A company_name='Tesla' ticker='TSLA' report_date='Q2 2024' raw_financials=RawFinancials(revenue=25.5, operating_income=1.6, eps=0.42) narrative='In Q2, we achieved record quarterly revenues despite a difficult operating environment. The Energy Storage business continues to grow rapidly, setting a record in Q2 with 9.4 GWh of deployments, resulting in record revenues and gross profits for the overall segment. We also saw a sequential rebound in vehicle deliveries in Q2 as overall consumer sentiment improved and we launched attractive financing options to offset the impact of sustained high interest rates. We recognized record regulatory credit revenues in Q2 as other OEMs are still behind on meeting emissions requirements. Global EV penetration returned to growth in Q2 and is taking share from ICE vehicles. We believe that a pure EV is the optimal vehicle design and will ultimately win over consumers as the myths on range, charging and service are debunked.'\n",
      "refined_model A revenue_projection=112.2 operating_income_projection=7.03 growth_rate=10.0 discount_rate=8.0 terminal_growth_rate=2.0 valuation_estimate=87.93 key_assumptions='Discount Rate: 8%, Terminal Growth Rate: 2%, Tax Rate: 25%, Revenue Growth (Years 1-5): 10% per annum, Revenue Growth (Years 6-10): 5% per annum, CAPEX as 7% of Revenue, Working Capital at 3% of Revenue, Depreciation at 10% per annum, Cost of Capital: 8%.' summary=\"Based on Tesla's Q2 2024 earnings where record quarterly revenue of $25.5 million (quarterly) was achieved, we annualized the performance (multiplied by 4) to establish a baseline annual revenue of approximately $102 million. Applying a conservative growth rate of 10% for next year leads to a revenue projection of around $112.2 million. Maintaining operating margin derived from Q2 (approximately 6.27%), the projected operating income is about $7.03 million. Utilizing a simplified DCF approach – adding back non-cash depreciation, subtracting CAPEX and working capital needs – the estimated enterprise value comes to roughly $87.93 million, using the given discount rate of 8% and terminal growth rate of 2%. These projections reflect Tesla’s strong performance in energy storage and vehicle deliveries amid challenging operating conditions, underpinned by robust demand drivers such as regulatory credits and rapid EV market expansion.\"\n",
      "<class '__main__.FinancialModelOutput'>\n",
      "Step refine_financial_model_company_a produced event CompanyModelEvent\n",
      "Running step cross_reference_models\n",
      "Step cross_reference_models produced no event\n",
      "refined_model B revenue_projection=210320.0 operating_income_projection=12320.0 growth_rate=10.0 discount_rate=8.0 terminal_growth_rate=2.0 valuation_estimate=154000.0 key_assumptions='Revenue growth of 10% per annum is applied for the next year, based on replicating Q2 values on an annual basis (by multiplying quarterly revenue by 4). Operating income is assumed to grow in line with revenue, maintaining the current operating margin. The tax rate is set at 25%, with capital expenditures estimated at 7% of revenue, working capital requirements at 3% of revenue, and depreciation at 10% of revenue. An 8% discount rate and a terminal growth rate of 2% are used to compute a simplified perpetual growth valuation using free cash flow derived from after-tax operating income adjusted for non-cash depreciation and reinvestment needs.' summary=\"Using Ford Motor Company's most recent Q2 financial data, we annualized the revenue (47.8 billion USD for Q2 becomes approximately 191.2 billion USD on an annual basis) and operating income figures to form our baseline. With an assumed annual revenue growth of 10%, next year's projected revenue is about 210.32 billion USD and operating income about 12.32 billion USD. Adjustments for taxes, CAPEX, working capital, and depreciation suggest a free cash flow of roughly 9.24 billion USD. Applying an 8% discount rate and a terminal growth rate of 2% yields an estimated enterprise value of approximately 154 billion USD. The model reflects a consistent margin profile and incorporates the company-specific outlook provided in the earnings deck.\"\n",
      "<class '__main__.FinancialModelOutput'>\n",
      "Step refine_financial_model_company_b produced event CompanyModelEvent\n",
      "Running step cross_reference_models\n",
      "Step cross_reference_models produced event StopEvent\n",
      "\n",
      "********Final Equity Research Memo:********\n",
      " company_a_model=FinancialModelOutput(revenue_projection=112.2, operating_income_projection=7.03, growth_rate=10.0, discount_rate=8.0, terminal_growth_rate=2.0, valuation_estimate=87.93, key_assumptions='Discount Rate: 8%, Terminal Growth Rate: 2%, Tax Rate: 25%, Revenue Growth (Years 1-5): 10% per annum, Revenue Growth (Years 6-10): 5% per annum, CAPEX as 7% of Revenue, Working Capital at 3% of Revenue, Depreciation at 10% per annum, Cost of Capital: 8%.', summary=\"Based on Tesla's Q2 2024 earnings where record quarterly revenue of $25.5 million (quarterly) was achieved, we annualized the performance (multiplied by 4) to establish a baseline annual revenue of approximately $102 million. Applying a conservative growth rate of 10% for next year leads to a revenue projection of around $112.2 million. Maintaining operating margin derived from Q2 (approximately 6.27%), the projected operating income is about $7.03 million. Utilizing a simplified DCF approach – adding back non-cash depreciation, subtracting CAPEX and working capital needs – the estimated enterprise value comes to roughly $87.93 million, using the given discount rate of 8% and terminal growth rate of 2%. These projections reflect Tesla’s strong performance in energy storage and vehicle deliveries amid challenging operating conditions, underpinned by robust demand drivers such as regulatory credits and rapid EV market expansion.\") company_b_model=FinancialModelOutput(revenue_projection=210320.0, operating_income_projection=12320.0, growth_rate=10.0, discount_rate=8.0, terminal_growth_rate=2.0, valuation_estimate=154000.0, key_assumptions='Revenue growth of 10% per annum is applied for the next year, based on replicating Q2 values on an annual basis (by multiplying quarterly revenue by 4). Operating income is assumed to grow in line with revenue, maintaining the current operating margin. The tax rate is set at 25%, with capital expenditures estimated at 7% of revenue, working capital requirements at 3% of revenue, and depreciation at 10% of revenue. An 8% discount rate and a terminal growth rate of 2% are used to compute a simplified perpetual growth valuation using free cash flow derived from after-tax operating income adjusted for non-cash depreciation and reinvestment needs.', summary=\"Using Ford Motor Company's most recent Q2 financial data, we annualized the revenue (47.8 billion USD for Q2 becomes approximately 191.2 billion USD on an annual basis) and operating income figures to form our baseline. With an assumed annual revenue growth of 10%, next year's projected revenue is about 210.32 billion USD and operating income about 12.32 billion USD. Adjustments for taxes, CAPEX, working capital, and depreciation suggest a free cash flow of roughly 9.24 billion USD. Applying an 8% discount rate and a terminal growth rate of 2% yields an estimated enterprise value of approximately 154 billion USD. The model reflects a consistent margin profile and incorporates the company-specific outlook provided in the earnings deck.\") comparative_analysis=ComparativeAnalysisOutput(comparative_analysis='Comparing the two refined models reveals several key differences. Company A’s (Tesla’s) model is based on a much smaller revenue base (annualized quarterly revenue of approximately $102 million, growing to $112.2 million with a 10% growth assumption) compared to Company B’s (Ford’s) model, which scales from a considerably larger quarterly figure to a projected annual revenue of roughly $210.32 billion. In Tesla’s model, the operating income projection is about $7.03 million, derived from maintaining a consistent operating margin from a strong Q2 performance. In contrast, Ford’s operating income is projected at about $12.32 billion, reflecting its vast operational scale and established footprint. \\n\\nBoth models assume similar growth rates (10% next year) and employ the same discount (8%) and terminal growth (2%) rates, but the underlying business model assumptions (e.g., CAPEX, working capital, and depreciation percentages) are applied to very different revenue levels, underscoring the distinct corporate scales and market positions. Additionally, the valuation estimate for Tesla is markedly lower at approximately $87.93 million compared to Ford’s multi-billion-dollar enterprise value, which highlights the relative stage and market capitalization disparities between the high-growth, innovation-driven Tesla and the mature, large-scale operation of Ford. \\n\\nFurthermore, Tesla’s model emphasizes its momentum in sectors like energy storage and EV deliveries, driven by factors such as regulatory credits and rapid market expansion, whereas Ford’s model reflects a traditional automotive giant with steady, albeit massive, revenue growth. \\n\\nOverall, the analysis—despite both companies using similar underlying financial assumptions—demonstrates that Tesla’s smaller scale and agility allow it to potentially achieve higher growth rates and innovative disruption, even though the absolute revenue and operating income values are much lower than Ford’s. This distinction is critical in the investment decision process.', overall_recommendation='Based on the comparative analysis, I recommend an investment in Tesla (Company A). Tesla’s refined model reflects robust growth potential, driven by its strong Q2 performance, efficient operating margins, and strategic positioning in the high-growth EV and energy storage markets. Despite its smaller scale compared to Ford, Tesla’s ability to capitalize on emerging demand drivers, innovation in technology, and future market expansion serves as a compelling case for investment. This recommendation rests on the expectation that Tesla’s growth trajectory and market disruption potential will enable it to outperform traditional automotive peers in a rapidly evolving industry, making it a strategic buy for investors seeking exposure to transformative technological and market trends.')\n"
     ]
    }
   ],
   "source": [
    "result = await workflow.run(\n",
    "    deck_path_a=\"./data/automotive_sector_analysis/tesla_q2_earnings.pdf\",\n",
    "    deck_path_b=\"./data/automotive_sector_analysis/ford_q2_earnings_press_release.pdf\",\n",
    ")\n",
    "final_memo = result[\"memo\"]\n",
    "print(\"\\n********Final Equity Research Memo:********\\n\", final_memo)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f00d58e0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "ComparativeAnalysisOutput(comparative_analysis='Comparing the two refined models reveals several key differences. Company A’s (Tesla’s) model is based on a much smaller revenue base (annualized quarterly revenue of approximately $102 million, growing to $112.2 million with a 10% growth assumption) compared to Company B’s (Ford’s) model, which scales from a considerably larger quarterly figure to a projected annual revenue of roughly $210.32 billion. In Tesla’s model, the operating income projection is about $7.03 million, derived from maintaining a consistent operating margin from a strong Q2 performance. In contrast, Ford’s operating income is projected at about $12.32 billion, reflecting its vast operational scale and established footprint. \\n\\nBoth models assume similar growth rates (10% next year) and employ the same discount (8%) and terminal growth (2%) rates, but the underlying business model assumptions (e.g., CAPEX, working capital, and depreciation percentages) are applied to very different revenue levels, underscoring the distinct corporate scales and market positions. Additionally, the valuation estimate for Tesla is markedly lower at approximately $87.93 million compared to Ford’s multi-billion-dollar enterprise value, which highlights the relative stage and market capitalization disparities between the high-growth, innovation-driven Tesla and the mature, large-scale operation of Ford. \\n\\nFurthermore, Tesla’s model emphasizes its momentum in sectors like energy storage and EV deliveries, driven by factors such as regulatory credits and rapid market expansion, whereas Ford’s model reflects a traditional automotive giant with steady, albeit massive, revenue growth. \\n\\nOverall, the analysis—despite both companies using similar underlying financial assumptions—demonstrates that Tesla’s smaller scale and agility allow it to potentially achieve higher growth rates and innovative disruption, even though the absolute revenue and operating income values are much lower than Ford’s. This distinction is critical in the investment decision process.', overall_recommendation='Based on the comparative analysis, I recommend an investment in Tesla (Company A). Tesla’s refined model reflects robust growth potential, driven by its strong Q2 performance, efficient operating margins, and strategic positioning in the high-growth EV and energy storage markets. Despite its smaller scale compared to Ford, Tesla’s ability to capitalize on emerging demand drivers, innovation in technology, and future market expansion serves as a compelling case for investment. This recommendation rests on the expectation that Tesla’s growth trajectory and market disruption potential will enable it to outperform traditional automotive peers in a rapidly evolving industry, making it a strategic buy for investors seeking exposure to transformative technological and market trends.')"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "final_memo.comparative_analysis"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llama_parse",
   "language": "python",
   "name": "llama_parse"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
